package com.ruoyi.finance.protal.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.finance.livestreaming.entity.SzOrder;
import com.ruoyi.finance.protal.shandpay.cashier.sdk.CertUtil;
import com.ruoyi.finance.protal.shandpay.cashier.sdk.CryptoUtil;
import com.ruoyi.finance.protal.shandpay.cashier.sdk.DemoBase;
import com.ruoyi.finance.protal.shandpay.cashier.sdk.SDKConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

@Slf4j
public class ShanDeCreateOrderH5 {
    //默认配置的是UTF-8
    public static String encoding = "UTF-8";

    public static Map<String, String> orderCreate(HttpServletRequest req, HttpServletResponse resp, SzOrder order) {
        Map<String, String> respDate = new LinkedHashMap<>();
        respDate.put("charset", "UTF-8");
        respDate.put("signType", "01");

        try {
            String reqAddr = "/gw/web/order/create";

            // 组后台报文
            JSONObject head = new JSONObject();
            head.put("version", "1.0");
            head.put("method", "sandpay.trade.orderCreate");
            head.put("productId", "00002000");
            head.put("accessType", "1");
            head.put("mid", "6888803119960");
            head.put("plMid", null);
            head.put("channelType", "07");
            head.put("reqTime", getCurrentTime());

            JSONObject body = new JSONObject();
            body.put("orderCode", order.getOrderId());
            body.put("userId", null);
            body.put("payerName", null);
            body.put("totalAmount", "000000000001");
            body.put("subject", order.getOrderName());
            body.put("body", order.getOrderDescription());
            body.put("txnTimeOut", getNextDayTime());
            body.put("payModeList", "[b2b,b2c,alipay,qrpay,qppay,rempay,wxjsbridge,wxjsapi]");
            body.put("notifyUrl", "http://dzcapp.cn/protal/notify");
            body.put("frontUrl", "http://dzcapp.cn");
            body.put("storeId", null);
            body.put("terminalId", null);
            body.put("operatorId", null);
            body.put("clearCycle", null);
            body.put("accountingMode", "02");
            body.put("bizExtendParams", null);
            body.put("merchExtendParams", null);
            body.put("accsplitInfo", null);
            body.put("extend", null);

            JSONObject data = new JSONObject();
            data.put("head", head);
            data.put("body", body);

            try {
                // 报文签名
                String reqSign = digitalSign(data.toJSONString());

                JSONObject respJson = new JSONObject();
                respJson.put("data", JSON.toJSONString(data));
                log.info("请求参数data："+data);
                respJson.put("sign", reqSign);
                log.info("签名sign："+reqSign);
               /* resp.getOutputStream().write(respJson.toJSONString().getBytes("UTF-8"));*/
                respDate.put("data", JSON.toJSONString(data));
                respDate.put("sign", reqSign);
                return respDate;
//                return respJson.toJSONString();
            } catch (Exception e) {
                log.error("CashierPayServlet post error <<<", e);
                return respDate;
            }
        } catch (Exception e) {
            log.error("H5支付参数创建失败");
            return respDate;
        }
    }

    /**
     * 签名方法
     *
     * @param data 待签名数据
     * @return
     * @throws Exception
     */
    public static String digitalSign(String data) throws Exception {
        if (null == data) {
            return null;
        } else {
            try {
                // 获取密钥配置
                /*String publicKeyPath = DynamicPropertyHelper.getStringProperty("sandpay.public.key", "").get();
                log.info("公钥路径："+publicKeyPath);
                String privateKeyPath = DynamicPropertyHelper.getStringProperty("sandpay.private.key", "").get();
                log.info("私钥路径："+privateKeyPath);
                String keyPassword = DynamicPropertyHelper.getStringProperty("sandpay.private.key.password", "").get();
                log.info("私钥密码："+keyPassword);
                // 初始化密钥信息
                CertUtil.init(publicKeyPath, privateKeyPath, keyPassword);*/

                // 加载配置文件
                SDKConfig.getConfig().loadPropertiesFromSrc();
                // 加载证书 初始化密钥信息
                CertUtil.init(SDKConfig.getConfig().getSandCertPath(), SDKConfig.getConfig().getSignCertPath(), SDKConfig.getConfig().getSignCertPwd());


                byte[] dataBytes = data.getBytes("UTF-8");
                // 签名
                String signData = new String(Base64.encodeBase64(CryptoUtil.digitalSign(dataBytes, CertUtil.getPrivateKey(), "SHA1WithRSA")), "UTF-8");
                return signData;
            } catch (Exception var6) {
                log.error("digitalSign(String, String)", var6);
                throw new Exception("签名异常", var6);
            }
        }
    }


    //请求时间 格式:YYYYMMDDhhmmss
    public static String getCurrentTime() {
        return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
    }

    // 订单超时时间 获取当前时间24小时后的时间
    public static String getNextDayTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, 1);
        return new SimpleDateFormat("yyyyMMddHHmmss").format(calendar.getTime());
    }

}
